<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 11:28
 */

namespace app\common\model;


use app\admin\model\PageResponse;
use think\Db;
use think\Model;

/**
 * Class Tag
 * @package app\common\model
 *
 * @property integer id
 * @property string title
 */
class Tag extends Model
{
    protected $table = 'tag';
    protected $pk = 'id';

    /**
     * 添加标签
     *
     * @param $title
     */
    public static function add($title) {
        $sql = <<<SQL
INSERT INTO tag (title) VALUES (:title)
SQL;
        Db::execute($sql, ['title' => $title]);
    }

    /**
     * 检查是是否存在
     *
     * @param $title
     * @return bool
     * @deprecated
     */
    public static function exists($title) {
        $sql = <<<SQL
SELECT exists(
SELECT * FROM tag WHERE title=:title
) e
SQL;
        $re = Db::query($sql, ['title' => $title]);

        return $re[0]['e'] ?? false;
    }

    /**
     * 给老师加标签
     *
     * @param $teacher_id
     * @param $tag_id
     */
    public static function addToTeacher($teacher_id, $tag_id) {
        $sql = 'INSERT INTO teacher_tag (teacher_id, tag_id) VALUES (:teacher_id, :tag_id) ON CONFLICT DO NOTHING';
        Db::execute($sql, [
            'teacher_id' => $teacher_id,
            'tag_id' => $tag_id
        ]);
    }

    public static function rmFromTeacher($teacher_id, $tag_id) {
        $sql = 'DELETE FROM teacher_tag WHERE teacher_id=:teacher_id AND tag_id=:tag_id';
        Db::execute($sql, [
            'teacher_id' => $teacher_id,
            'tag_id' => $tag_id
        ]);
    }

    /**
     * 获取老师的标签
     *
     * @param $teacher_id
     * @return mixed
     */
    public static function getByTeacher($teacher_id) {
        $sql = <<<SQL
SELECT * FROM tag 
WHERE id IN (SELECT tt.tag_id FROM teacher_tag tt WHERE tt.teacher_id=:teacher_id)
SQL;
        $list = Db::query($sql, ['teacher_id' => $teacher_id]);
        return $list;
    }

}